#!/usr/bin/env python
#encoding=utf-8

from util import download_file
from chapter_download_thread import ChapterDownloadThread 
import os

def download_chapters(chapter_list, save_path):
    download_thread_list = []
    print('============= Start new chapters =============')
    for chapter in chapter_list:
        download_thread = ChapterDownloadThread(chapter, save_path)
        download_thread.start()
        print('Start thread: ' + download_thread.getName())
        download_thread_list.append(download_thread)

    for download_thread in download_thread_list:
        download_thread.join()
        print('Thread: ' + download_thread.getName() + ' Done')
    print('All thread done.')

def download_lecture(chapter_list, save_path):
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    print('Download lecture: ')
    download_chapters(chapter_list, save_path)
    pass

def download_practice(chapter_list, save_path):
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    print('Download practice: ')
    download_chapters(chapter_list, save_path)
    pass

def download_phone_video(chapter_list, save_path):
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    print('Download phone video: ')
    download_chapters(chapter_list, save_path)
    pass

def download_course(course_resource, course_name, save_path):
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    print('Download course: ' + course_name)
    
    lecture_save_path = save_path + '/' + 'lecture'
    download_lecture(course_resource['lecture'], lecture_save_path)

    practice_save_path = save_path + '/' + 'practice'
    download_practice(course_resource['practice'], practice_save_path)

    phone_video_save_path = save_path + '/' + 'phone_video'
    download_phone_video(course_resource['phone_video'], phone_video_save_path)
    pass

def download(resource, save_path):
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    resource_list = resource['course_list'] 
    for item in resource_list:
        download_course(item['resource'], item['course_name'], save_path + '/' + item['course_name'])
    pass
